/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.jmh.benchmark.counter.impl;

import java.util.concurrent.locks.ReentrantLock;

import me.ijleex.jmh.benchmark.counter.Counter;

/**
 * LockCounter.
 *
 * @author liym
 * @since 2020-05-27 12:17 新建
 */
public class LockCounter implements Counter {

    private final ReentrantLock lock;

    private long counter;

    /**
     * @param fair 是否使用公平锁
     */
    public LockCounter(boolean fair) {
        this.lock = new ReentrantLock(fair);
    }

    @Override
    public void increment() {
        this.lock.lock();
        try {
            ++this.counter;
        } finally {
            this.lock.unlock();
        }
    }

    @Override
    public long getCount() {
        this.lock.unlock();
        try {
            return this.counter;
        } finally {
            this.lock.unlock();
        }
    }

}
